#include <string.h>

#include "lib.h"
#include "pkglist.h"
#include "pkgdesc.h"

PackageList::~PackageList()
{
	while (head)
	{
		tail = head;
		head = head->getNext();
		delete tail;
	}
	tail = (PackageDescription*)0;

	count = 0;
}

PackageDescription*
PackageList::getItem(int32 index)
{
	PackageDescription* result = head;

	while (result && index-- > 0)
		result = result->getNext();

	return result;
}

PackageDescription*
PackageList::getItem(char* Name, char* ZipName, int32* index)
{
	PackageDescription* probe = head;
		
	// successful match if either Package name or ZipName are same.
	// purpose:  prevent serving duplicates or versions of the same pkg
	//
	*index = 0;

	while (probe &&
		0 != probe->getZipName().caseCompare(ZipName) &&
		0 != probe->getName().caseCompare(Name))
	{
		probe = probe->getNext();
		++(*index);
	}

	if (!probe)
		*index = -1;

	return probe;
}

void
PackageList::addItem(PackageDescription* item)
{
	if (item)
	{
		++count;

		item->setNext((PackageDescription*)0);

		if (tail)
			tail->setNext(item);
		else
			head = item;

		tail = item;
	}
}

void
PackageList::removeItem(PackageDescription* kill)
{
	PackageDescription* probe = head;
	PackageDescription* prev = (PackageDescription*)0;
	
	while (probe && probe != kill)
	{
		prev = probe;
		probe = probe->getNext();
	}

	if (probe)
	{
		--count;

		if (prev)
		{
			prev->setNext(probe->getNext());

			if (probe == tail)
				tail = prev;
		}
		else
		{
			head = probe->getNext();
			if (!head)
				tail = head;
		}
	}
}

bool8
PackageList::contains(char* Name, char* ZipName)
{
	int32 index = -1;
	return (bool8)((PackageDescription*)0 != getItem(Name, ZipName, &index));
}
